#! /usr/bin/python
#-*- encoding utf-8 -*-
'''
Usage: Http Server using socket
'''

import socket, threading

class ConnectHandler(threading.Thread):

    def setConnect(self, connect):
        self.conn = connect

    def run(self): 
        request = self.conn.recv(1024)
        content = '''
        HTTP/1.1 200 ok
        Content-Type: text/html
        <head>
        <title>WOW</title>
        </head>
        <html>
        <p>Wow, Python Server</p>
        </html>        
        '''
        method = request.split(' ')[0]
        src = request.split(' ')[1]
        if method == 'GET':
           self.conn.sendall(content)
        self.conn.close()

class HttpServer:

    def __init__(self, ip='127.0.0.1', port = 9000):
        self.ip = ip
        self.port = port
    def start(self):
        print("HttpServer start (%s:%d)"%(self.ip,self.port))
   
        client_num = 1
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1000 * 10)
        sock.bind((self.ip, self.port))
 
 
        while True:
            sock.listen(3)
            conn, addr = sock.accept()
            print("client connecting:", client_num)
            client_num +=1
            con_handler = ConnectHandler()
            con_handler.setConnect(conn)
            con_handler.start()
        sock.close()

        print("HttpServer close, bye-bye")

if __name__ == '__main__':
    server = HttpServer()
    server.start()        
